//
//  MCTraindetailPlanVc.swift
//  MCBodyBuildingPro
//
//  Created by Renlvshijie on 2023/5/31.
//

import UIKit
import QMUIKit
import Toast_Swift
import ObjectMapper
import SnapKit
import Kingfisher
import JKSwiftExtension

class MCTraindetailPlanVc: MCBaseVc {
    
    public var ids:String?
    
    @IBOutlet weak var trainPlanTableView: UITableView!
    
    let mcTrainDetailIdentifier = "mcTrainDetailIdentifier"
    
    let mcTrainDetailRecommandIdentifier = "mcTrainDetailRecommandIdentifier"
    
    let mcintrumentsCollectionIdentifier = "mcintrumentsCollectionIdentifier"
    
    var trainDetailHeaderView:MCTrainDetailHeaderView!
    
    var instumentsDataSource:Array = [MCTrainDetailInstrument?]()
    
    var actionPlanDetailActionListModel:Array = [MCTrainDetailActionPlanDetailList?]()
    
    @IBOutlet weak var enteraddSender: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.qmui_color(withHexString: "F7F7F9")
        self.navigationItem.title = "训练计划"
        
        enteraddSender.layer.cornerRadius = 25.0
        enteraddSender.layer.masksToBounds = true
        enteraddSender.layer.borderColor = UIColor.qmui_color(withHexString: "#10151C")?.cgColor
        enteraddSender.layer.borderWidth = 1.0
        
        self.trainPlanTableView.register(UINib(nibName: "MCTrainDetailCell", bundle: Bundle.main), forCellReuseIdentifier: mcTrainDetailIdentifier)
        self.trainPlanTableView.register(UINib(nibName: "MCTrainRecommandCell", bundle: Bundle.main), forCellReuseIdentifier: mcTrainDetailRecommandIdentifier)
        
        let trainDetailHeaderView = MCTrainDetailHeaderView.initHeaderView()
        
        let jiCollectionViewLayout = UICollectionViewFlowLayout.init()
        jiCollectionViewLayout.scrollDirection = .horizontal
        trainDetailHeaderView.jiCollectionVIew.setCollectionViewLayout(jiCollectionViewLayout, animated: true)
        trainDetailHeaderView.jiCollectionVIew.dataSource = self
        trainDetailHeaderView.jiCollectionVIew.delegate = self
        self.trainDetailHeaderView = trainDetailHeaderView
        
        self.trainPlanTableView.tableHeaderView = trainDetailHeaderView
        
        trainDetailHeaderView.jiCollectionVIew.register(UINib(nibName: "MCTrainInterumentCollectionCell", bundle: Bundle.main), forCellWithReuseIdentifier: mcintrumentsCollectionIdentifier)
        
        self.getTranDetailPlanData(ids: ids)
        
    }
    
    
    //详情页
    func getTranDetailPlanData(ids:String?) -> Void {
        NetWorkRequest(MCTrainDetailPlanApi.trainDetailPlanData(ids:ids)) { ResponseModel in
            if ResponseModel.code == 200 {
                let trianModel = MCTrainDetaillistModel.init(JSONString: ResponseModel.dataString)
                
                self.trainDetailHeaderView.headerIconImV.kf.setImage(with: URL(string:trianModel?.planUrl ?? ""))
                self.trainDetailHeaderView.titleIconLabel.text = trianModel?.planName ?? ""
                
                self.trainDetailHeaderView.timesLabel.text = "≈ \(String(describing:((trianModel?.planNeedTime ?? 0) / 60)))分钟"
                
                let paddingLabel = QMUIButton.init()
                paddingLabel.backgroundColor = UIColor.qmui_color(withHexString:"#35DE94")?.withAlphaComponent(0.1)
                paddingLabel.setTitleColor( UIColor.qmui_color(withHexString: "#35DE94"), for: .normal)
                if trianModel?.planLevel == nil {
                    
                }else{
                    paddingLabel.setTitle("L\(String(describing:(trianModel?.planLevel)!))", for: .normal)
                }
               
                paddingLabel.contentEdgeInsets = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10)
                paddingLabel.layer.cornerRadius = 5
                paddingLabel.titleLabel?.font = UIFont(name: "PingFangSC-Regular", size: 10)
                paddingLabel.layer.masksToBounds = true
                self.trainDetailHeaderView.labelLayoutView.addSubview(paddingLabel)
                //介绍
                self.trainDetailHeaderView.jieshaoLabel.text = trianModel?.introduce ?? ""
                
                if trianModel?.positions?.isEmpty == false {
                    var dictArray:Array = [String]()
                    for position:MCTrainDetailPosition in (trianModel?.positions)! {
                        dictArray.append(position.dictValue ?? "")
                    }
                    
                    self.trainDetailHeaderView.trainPositionsLabel.text = dictArray.joined(separator: ",")
                }else {
                    self.trainDetailHeaderView.trainPositionsLabel.text = ""
                }
                
                self.instumentsDataSource.append(contentsOf: trianModel?.instruments ?? [])
                
                self.trainDetailHeaderView.jiCollectionVIew.reloadData()
                
                if trianModel?.actionPlanDetailList?.isEmpty == false {
                    self.actionPlanDetailActionListModel.append(contentsOf: trianModel?.actionPlanDetailList ?? [])
                    self.trainPlanTableView.reloadSections(IndexSet.init(integer: 0), with: .top)
                }
                 
                
                if trianModel?.muscles?.isEmpty == false {
                    var jirouArray:Array = [String]()
                    for position:MCTrainDetailPosition in (trianModel?.muscles)! {
                        jirouArray.append(position.dictValue ?? "")
                    }
                    self.trainDetailHeaderView.jirouLabel.text = jirouArray.joined(separator: ",")
                }else{
                    self.trainDetailHeaderView.jirouLabel.text = ""
                }
                
            }else{
                self.view.makeToast("网路失败",position: .center)
            }
            
        } failureCallback: { ResponseModel in
            self.view.makeToast("网路失败",position: .center)
        }
    }
    
  
    //加入计划
    @IBAction func addenterBtn(_ sender: UIButton) {
        let oneMonthSelectVc = MCOneMonthSelectVc.init()
        oneMonthSelectVc.ids = self.ids ?? ""
        self.navigationController?.pushViewController(oneMonthSelectVc, animated: true)
    }
    
    //开始训练
    @IBAction func trainStartSender(_ sender: UIButton) {
        
        let ageInfo = UserDefaults.standard.object(forKey: "promptAgainInfo")
        
        if (ageInfo != nil) == true {
            let videoTrainNotfitVc = MCVIdeoTranNofitVc.init()
            videoTrainNotfitVc.ids = self.ids ?? ""
            self.navigationController?.pushViewController(videoTrainNotfitVc, animated: true)
        }else{
            let trainNotifitVc = MCTrainNotifitVc.init()
            trainNotifitVc.userId = self.ids ?? ""
            self.navigationController?.pushViewController(trainNotifitVc, animated: true)
        }
        
    }
}

extension MCTraindetailPlanVc:UITableViewDelegate,UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
        
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return self.actionPlanDetailActionListModel.count
        }else{
            return 1
        }
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            let actionList = self.actionPlanDetailActionListModel[indexPath.row]
            
            if  (actionList?.actionPlanDetailActionList?.count ?? 0) % 3 == 0 {
                return CGFloat(((actionList?.actionPlanDetailActionList?.count ?? 0) / 3 ) * 170)
            }else {
                return CGFloat(((actionList?.actionPlanDetailActionList?.count ?? 0) / 3 + 1) * 170)
            }
            
        }else {
            return 140
        }
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section == 0 {
            let cell:MCTrainDetailCell = tableView.dequeueReusableCell(withIdentifier: mcTrainDetailIdentifier, for: indexPath) as! MCTrainDetailCell
            let actionList = self.actionPlanDetailActionListModel[indexPath.row]
            
            cell.actionPlanDetailActionListModelInfo = actionList?.actionPlanDetailActionList
            cell.actionPlanListModel = actionList
            
            cell.headerSection = (indexPath.row + 1)
            
            return cell
        }else{
            let cell:MCTrainRecommandCell = tableView.dequeueReusableCell(withIdentifier: mcTrainDetailRecommandIdentifier, for: indexPath) as! MCTrainRecommandCell
            
            return cell
        }
        
      
    }
    
}

extension MCTraindetailPlanVc:UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 120, height: 120)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 10
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 10
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.instumentsDataSource.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell:MCTrainInterumentCollectionCell = collectionView.dequeueReusableCell(withReuseIdentifier: mcintrumentsCollectionIdentifier, for: indexPath) as! MCTrainInterumentCollectionCell
       
        let jixieModel = self.instumentsDataSource[indexPath.row]
        
        cell.headerImageVIew.kf.setImage(with: URL(string: jixieModel?.previewPic ?? ""))
        cell.titleInfoActionLabel.text = jixieModel?.zhName ?? ""
        
        
        return cell
    }
}
